import React, { useState, useEffect } from 'react';
import { getToken } from '../login/loginApi';

interface AuditRecord {
  audit_record_id: string;
  storage_key: string;
  audit_rule_id: string;
  result: string;
  suggestions: Array<{
    original: string;
    suggestion: string[];
  }>;
  create_at: string;
}

const apiHost = import.meta.env.VITE_API_HOST || '';

const AuditTimeline = () => {
  const [auditRecordId, setAuditRecordId] = useState('');
  const [storageKey, setStorageKey] = useState('');
  const [data, setData] = useState<AuditRecord[]>([]);

  useEffect(() => {
    fetchData(); // 页面加载时自动获取数据
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch(
        `${apiHost}/documents/auditByGpt/storageKey/list`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${getToken()}`,
          },
          body: JSON.stringify({
            audit_record_id: auditRecordId,
            storage_key: storageKey,
          }),
        },
      );

      if (!response.ok) {
        throw new Error('Network response was not ok.');
      }

      const result = await response.json();
      setData(result.data);
    } catch (error) {
      console.error('There was an error fetching the data:', error);
      setData([]);
    }
  };

  return (
    <div className="container mx-auto p-4">
      <div className="flex gap-4 mb-4">
        <input
          type="text"
          placeholder="审计记录 ID"
          value={auditRecordId}
          onChange={(e) => setAuditRecordId(e.target.value)}
          className="input input-bordered w-full max-w-xs rounded-none border-2 border-gray-300 focus:border-blue-500 focus:ring-0"
        />
        <input
          type="text"
          placeholder="存储键值"
          value={storageKey}
          onChange={(e) => setStorageKey(e.target.value)}
          className="input input-bordered w-full max-w-xs rounded-none border-2 border-gray-300 focus:border-green-500 focus:ring-0"
        />
        <button
          onClick={fetchData}
          className="btn bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-none"
        >
          查询
        </button>
      </div>
      <div className="timeline">
        {data.map((record, index) => (
          <div key={index} className="timeline-item">
            <div className="timeline-marker"></div>
            <div className="timeline-content p-4 rounded-lg shadow">
              <p><strong>审计记录 ID:</strong> {record.audit_record_id}</p>
              <p><strong>存储键值:</strong> {record.storage_key}</p>
              <p><strong>审计规则 ID:</strong> {record.audit_rule_id}</p>
              <p><strong>结果:</strong> {record.result}</p>
              <div>
                <strong>建议:</strong>
                {record.suggestions.map((suggestion, sIndex) => (
                  <div key={sIndex}>
                    <p dangerouslySetInnerHTML={{__html: suggestion.original}}></p>
                    {suggestion.suggestion.map((text, tIndex) => (
                      <p key={tIndex}>{text}</p>
                    ))}
                  </div>
                ))}
              </div>
              <p><strong>创建时间:</strong> {record.create_at}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default AuditTimeline;